<?php
/**
 * Created by PhpStorm.
 * User: paulLu
 * Date: 2016/2/22
 * Time: 13:57
 */
namespace App\Http\Controllers\Circle;
use App\Http\Controllers\ApiController;
use App\Http\Components\UserComponent;
use App\library\juhe\Identify;
use App\library\UtilFunction;
use App\Models\CircleModel;
use App\Models\UserModel;
use App\Models\ConfigModel;
use App\Models\UserSettingModel;
use App\Models\UserProfileModel;
use App\Models\UserAccountModel;
use Illuminate\Http\Request;

use App\Http\Components\OuterDataComponent;
use App\library\UtilRegular;

/**
 * 送花
 */
class FlowerController extends ApiController{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->flower($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }


    /**
     * 送花
     */
    public function flower(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $cid = $request->input('cid');
        if(empty($cid)){
            return $this->json('0','凹凸圈ID不能为空');
        }
        $circle = CircleModel::where("id",$cid)->first();
        if(!$circle){
            return $this->json('0','该记录不存在');
        }elseif($circle->user_id == $user_id){
            return $this->json('0','自己不能给自己送花');
        }
        $config = new ConfigModel();
        $flower_price = $config->get_value('flow_price');
        $userAccount = UserAccountModel::where("user_id",$user_id)->first()->toArray();
        UserComponent::checkBalance($userAccount,$flower_price);

        $result = CircleModel::where("id",$cid)->increment("flower_num",1);
        if($result){
            UserAccountModel::where("user_id",$circle->user_id)->increment("flower_num",1);
            //添加记录
            UserComponent::price_save("flower",$user_id,$flower_price,-1);
            UserComponent::price_save("flower",$circle->user_id,$flower_price,1);
            return $this->json('1','送花成功');
        }else{
            return $this->json('0','保存失败');
        }

    }



}